<?php

    defined('BASEPATH') OR exit('No direct script access allowed');

    // This can be removed if you use __autoload() in config.php OR use Modular Extensions
    require APPPATH.'/libraries/REST_Controller.php';

    class RentBooking extends REST_Controller
    {

        public function __construct()
        {
            parent::__construct();
            if(!class_exists("translate"))
                $this->translate=& $this->factory->create('translate', 'foo', 'bar');

        }

//        function locations_get()
//        {
//            $locations=array(
//                array('id' => 1, 'text' => 'Budva - Globtour Office', 'value' => '0'),
//                array('id' => 2, 'text' => 'Budva - Hotel Avala', 'value' => '0'),
//                array('id' => 3, 'text' => 'Budva - Hotel Slovenska Plaza', 'value' => '0'),
//                array('id' => 4, 'text' => 'Budva - Hotel Mediteran', 'value' => '0'),
//                array('id' => 5, 'text' => 'Budva - Hotel Iberostar', 'value' => '0'),
//                array('id' => 6, 'text' => 'Petrovac - Hotel Palas', 'value' => '0'),
//                array('id' => 7, 'text' => 'TIVAT - Airport +15 &#8364;', 'value' => '15'),
//                array('id' => 8, 'text' => 'TIVAT - Hotel Palma +15 &#8364;', 'value' => '15'),
//                array('id' => 9, 'text' => 'KOTOR - Risan +15 &#8364;', 'value' => '15'),
//                array('id' => 10, 'text' => 'KOTOR - Perast +15 &#8364;', 'value' => '15'),
//                array('id' => 11, 'text' => 'BAR - Hotel Princess +15 &#8364;', 'value' => '15'),
//                array('id' => 12, 'text' => 'ULCINJ - Hotel Otrant +15 &#8364;', 'value' => '15'),
//                array('id' => 13, 'text' => 'ULCINJ - Hotel Ada Bojana +15 &#8364;', 'value' => '15'),
//                array('id' => 14, 'text' => 'PODGORICA - Airport +15 &#8364;', 'value' => '15'),
//                array('id' => 15, 'text' => 'PODGORICA - Hotel Crna Gora +15 &#8364;', 'value' => '15'),
//                array('id' => 16, 'text' => 'PODGORICA - Hotel Podgorica +15 &#8364;', 'value' => '15')
//            );
//
//            $this->response($locations, 200); // 200 being the HTTP response code
//
//        }

        function locations_get()
        {
            $q="SELECT 
                locations.name, locations.price, locations.ID, locations.is_return, locations.x_pos, locations.y_pos, locations.contact,
                cities.name as city_name
                FROM locations
                LEFT JOIN cities ON locations.cities_ID = cities.ID  
                ORDER BY locations.ID ASC";
            $res=$this->db->query($q)->result_array();

            // Do create location by cities for optgroup
            $locations=array();

            $cnt=count($res);

            if($cnt > 0)
            {

                $locations[$res[0]['city_name']][]=$res[0];

                for($i=1; $i < $cnt; $i++):

                    $locations[$res[$i]['city_name']][]=$res[$i];

                // ova provjera nije potrebna, 
                // samo dodajenmo u asocijativni niz ukoliko kljuc postoji ili ne
//                    if(array_key_exists($res[$i]['city_name'], $locations))
//                    {
//                        $locations[$res[$i]['city_name']][]=$res[$i];
//                    }
//                    else
//                    {
//                        $locations[$res[$i]['city_name']][]=$res[$i];
//                    }

                endfor;

                $this->response($locations, 200);
            }else
                $this->response($locations[]='No results in DB', 200);

        }

        function all_cars_get()
        {

            $q='
            SELECT car.*, gallery.path as g_path, pictures.filename as f_name
            FROM car
            LEFT JOIN gallery ON car.id = gallery.`posts_ID`
            LEFT JOIN pictures ON gallery.ID = pictures.gallery_ID
            AND pictures.ID=
            (
            SELECT pictures.ID
            FROM pictures
            WHERE pictures.gallery_ID = gallery.ID
            ORDER BY pictures.order ASC, pictures.ID ASC
            LIMIT 1, 1 
            )
            where user_id = 7 order by day13price asc
            ';


            $dbRet=$this->db->query($q);
            $this->_proces_response($dbRet);

        }

        function available_cars_post()
        {

            $dateTimeFrom=strtotime($this->input->get_post('dateTimeFrom'));
            $dateTimeTo=strtotime($this->input->get_post('dateTimeTo'));
            $days=calculateDays($dateTimeFrom, $dateTimeTo, FALSE);

            /* $dateTimeFrom = strtotime($this->get('dateTimeFrom'));
              $dateTimeTo = strtotime($this->get('dateTimeTo'));
              $days = calculateDays($dateTimeFrom, $dateTimeTo, FALSE); */

            /* $dateTimeFrom = strtotime('18.02.2012 08:00:00');
              $dateTimeTo = strtotime('19.02.2012 08:00:00'); */

            if(!$dateTimeFrom || !$dateTimeTo)
            {

                $this->response(array('info' => 'Enter dates:'), 200); // 200 being the HTTP response code
                return FALSE;
            }

            if($dateTimeFrom >= $dateTimeTo)
            {

                $this->response(array('info' => 'Wrong date.'), 200); // 200 being the HTTP response code
                return FALSE;
            }

            /* if($days > 15) {

              $this->response(array('info'=>'Max 15 days.'), 200); // 200 being the HTTP response code
              return FALSE;
              } */

            $dbRet=$this->getAvailable($dateTimeFrom, $dateTimeTo);

            $this->_proces_response($dbRet);

        }

        function isAvailiable_post()
        {
            $datetimefrom=strtotime($this->input->get_post('dateTimeFrom'));
            $datetimeto=strtotime($this->input->get_post('dateTimeTo'));
            $car_id=$this->input->get_post('car_id');

            /* $datetimefrom = strtotime('25.04.2012 08:00');
              $datetimeto = strtotime('26.04.2012 08:00');
              $car_id = 23; */


            // select not availiable car
            $query="select * from carbooking
            where ((datefrom between ".$datetimefrom." and ".$datetimeto.")
            or (dateto between ".$datetimefrom." and ".$datetimeto.")
            or((".$datetimefrom." > datefrom) and (".$datetimefrom." < dateto) or (".$datetimeto." > datefrom and ".$datetimeto." < dateto)))
            and (status = 1 or status = 3 or status = 0) and user_id = 7 and carid = $car_id
            group by carid order by carid desc";



            // if count is 1, car is not availbale
            $res=$this->db->query($query)->result_array();
            //print_r($this->db->last_query());
            $count=count($res);
            //echo '<br><br>';
            //print_r($res);
            $this->response(array('available' => $count), 200);

        }

        function getAvailable($datetimefrom, $datetimeto)
        {

            $query="select * from carbooking
            where ((datefrom between ".$datetimefrom." and ".$datetimeto.")
            or (dateto between ".$datetimefrom." and ".$datetimeto.")
            or((".$datetimefrom." > datefrom) and (".$datetimefrom." < dateto) or (".$datetimeto." > datefrom and ".$datetimeto." < dateto)))
            and (status = 1 or status = 3 or status = 0) and user_id = 7
            group by carid order by carid desc";

            $notavailable=array();

            $q=$this->db->query($query);

            foreach($this->db->query($query)->result_array() as $one)
            {
                $notavailable[]=$one['carid'];
            }

            //      now list available cars
            if(count($notavailable) > 0)
            {
                $nstr=implode(',', $notavailable);
                $q=$this->db->query("

                    SELECT car.*, gallery.path as g_path, pictures.filename as f_name
                    FROM car
                    LEFT JOIN gallery ON car.id = gallery.`posts_ID`
                    LEFT JOIN pictures ON gallery.ID = pictures.gallery_ID
                    AND pictures.ID=
                    (
                    SELECT pictures.ID
                    FROM pictures
                    WHERE pictures.gallery_ID = gallery.ID
                    ORDER BY pictures.order ASC, pictures.ID ASC
                    LIMIT 1, 1  
                    )
                    where car.id not in (".$nstr.") and (user_id = 7) order by day13price asc
                ");
            }
            else
            {
                $q=$this->db->query("
                    SELECT car.*, gallery.path as g_path, pictures.filename as f_name
                    FROM car
                    LEFT JOIN gallery ON car.id = gallery.`posts_ID`
                    LEFT JOIN pictures ON gallery.ID = pictures.gallery_ID
                    AND pictures.ID=
                    (
                    SELECT pictures.ID
                    FROM pictures
                    WHERE pictures.gallery_ID = gallery.ID
                    ORDER BY pictures.order ASC, pictures.ID ASC
                    LIMIT 1, 1  
                    )
                    where user_id = 7 order by day13price asc
                ");
            }

            return $q;

        }

        function get_car_post()
        {

            $id=$this->input->get_post('id');
            //$id = $this->get('id');

            $q='
            SELECT car.*, gallery.path as g_path, pictures.filename as f_name
            FROM car
            LEFT JOIN gallery ON car.id = gallery.`posts_ID`
            LEFT JOIN pictures ON gallery.ID = pictures.gallery_ID
            AND pictures.ID=
            (
            SELECT pictures.ID
            FROM pictures
            WHERE pictures.gallery_ID = gallery.ID
            ORDER BY pictures.order ASC, pictures.ID ASC
            LIMIT 1, 1
            )
            where user_id = 7 AND car.id='.$id.' order by day13price asc
            ';

            $dbRet=$this->db->query($q);
            $this->_proces_response($dbRet);

        }

        function get_car_images_post()
        {

            $id=$this->input->get_post('id');
            //$id = $this->get('id');

            $gallery=$this->db->get_where('gallery', array('posts_ID' => $id))->row_array();

            $this->db->order_by('order asc, ID asc');

            $this->db->limit(999, 2);

            $dbRet=$this->db->get_where('pictures', array('gallery_ID' => $gallery['ID']));

            $this->_proces_response($dbRet);

        }

        function get_car_video_post()
        {

            $id=$this->input->get_post('id');
            //$id = $this->get('id');

            $gallery=$this->db->get_where('gallery', array('posts_ID' => $id))->row_array();

            $this->db->order_by('order asc, ID asc');

            $dbRet=$this->db->get_where('videos', array('gallery_ID' => $gallery['ID']));

            $this->_proces_response($dbRet);

        }

        function get_car_bigger_post()
        {

            $id=$this->input->get_post('id');
            $dateTimeFrom=strtotime($this->input->get_post('dateTimeFrom'));
            $dateTimeTo=strtotime($this->input->get_post('dateTimeTo'));

            /* $id = 31;
              $dateTimeFrom = strtotime('14.03.2012 08:00:00');
              $dateTimeTo = strtotime('15.03.2012 08:00:00'); */

            $dbRet=$this->getAvailable($dateTimeFrom, $dateTimeTo)->result_array();

            //print_r($dbRet);
            $z=0;
            foreach($dbRet as $row)
            {
                //echo 'row->id:'.$row['id'].'<br />';
                if($row['id'] == $id)
                {
                    break;
                }
                else
                {
                    $z++;
                }
            }

            $q='
            SELECT car.*, gallery.path as g_path, pictures.filename as f_name
            FROM car
            LEFT JOIN gallery ON car.id = gallery.`posts_ID`
            LEFT JOIN pictures ON gallery.ID = pictures.gallery_ID
            AND pictures.ID=
            (
            SELECT pictures.ID
            FROM pictures
            WHERE pictures.gallery_ID = gallery.ID
            ORDER BY pictures.order ASC, pictures.ID ASC
            LIMIT 0, 1  
            )
            where user_id = 7 AND car.id='.$dbRet[$z + 1]['id'].' order by day13price asc
            ';

            $dbRet2=$this->db->query($q);
            $this->_proces_response($dbRet2);

        }

        function accessories_post()
        {

            $id=$this->input->get_post('id');
            //$id = $this->get('id');
            //$id = 34;

            $query='
            SELECT 
            accessoriesitem.carId, accessoriesitem.accessoryId, 
            accessorydescription.id, accessorydescription.type, accessorydescription.description, accessorydescription.price
            FROM `accessoriesitem` LEFT JOIN accessorydescription ON
            accessoriesitem.accessoryId = accessorydescription.id
            WHERE accessoriesitem.carId = '.$id.'
            ';

            $dbRet=$this->db->query($query);
            $this->_proces_response($dbRet);

        }

        function process_booking_post()
        {

            $this->load->library('class_model/booking');

            $session=$this->input->get_post('session');

            /* $session = array
              (
              'session_id' => '6147e0b72d9893f31856b136783b747a',
              'ip_address' => '78.155.52.2',
              'user_agent' => 'Mozilla/5.0 (Windows NT 6.1; rv:10.0.2) Gecko/2010',
              'last_activity' => '1330799887',
              'fullfrom' => '08:00',
              'fullto' => '08:00',
              'pickup_date' => '10.03.2012',
              'return_date' => '11.03.2012',
              'pickup_loc_id' => 3,
              'pickup_loc_text' => 'TIVAT Airport +15 &#8364;',
              'pickup_loc_value' => 15,
              'return_loc_id' => 2,
              'return_loc_text' => 'TIVAT Airport +15 &#8364',
              'return_loc_value' => 15,
              'no_days' => 1,
              'tot_price' => 85,
              'car_id' => 36,
              'cust_name' => 'a',
              'cust_email' => 'a@a.a',
              'cust_phone' => 'a',
              'cust_note' => '',
              'cust_terms' => 1,
              'source_info'=>'www.novisajt.com',
              'day_price'=>35
              ); */


            if(!isset($session))
            {
                $this->response(array('info' => 'No session data'), 200);
                return FALSE;
            }
            if(!isset($session['pickup_date']))
            {
                $this->response(array('info' => 'No pickup_date'), 200);
                return FALSE;
            }
            if(!isset($session['return_date']))
            {
                $this->response(array('info' => 'No return_date'), 200);
                return FALSE;
            }
            if(!isset($session['fullfrom']))
            {
                $this->response(array('info' => 'No fullfrom'), 200);
                return FALSE;
            }
            if(!isset($session['fullto']))
            {
                $this->response(array('info' => 'No fullto'), 200);
                return FALSE;
            }
            if(!isset($session['car_id']))
            {
                $this->response(array('info' => 'No car_id'), 200);
                return FALSE;
            }
            if(!isset($session['tot_price']))
            {
                $this->response(array('info' => 'No total_price'), 200);
                return FALSE;
            }

            $dbRet=$this->booking->AddToBooking($session);

            $this->_proces_response($dbRet);

        }

        function show_order_post()
        {

            $this->load->library('class_model/booking');

            $booking_id=$this->input->get_post('carbooking_id');
            //$booking_id = $this->get('carbooking_id');
            //$booking_id = 777;

            if(!isset($booking_id) || $booking_id == NULL)
            {
                $this->response(array('info' => 'No booking_id.'), 200); // 200 being the HTTP response code
                return FALSE;
            }

            $data=array();

            $dbRet=$this->booking->ShowOrder_1($booking_id);
            $data[0]=$this->_proces_response_2($dbRet);

            $dbRet=$this->booking->ShowOrder_2($booking_id);
            $data[1]=$this->_proces_response_2($dbRet);

            $this->response($data, 200); // 200 being the HTTP response code

        }

        function show_transaction_post()
        {

            $this->load->library('class_model/booking');

            $trans_id=$this->input->get_post('trans_id');

            $dbRet=$this->booking->ShowTransaction($trans_id);
            $this->_proces_response($dbRet);

        }

        function find_type_post()
        {

            $this->load->library('class_model/booking');

            $trans_id=$this->input->get_post('trans_id');
            //$trans_id = 'cPGLThCq8FcHYNFVbuDuYNI4hkk=';

            $dbRet=$this->booking->FindType($trans_id);

            if($dbRet != 'error')
            {
                $this->response(array('type' => $dbRet), 200); // 200 being the HTTP response code         
            }
            else
            {
                $this->response(array('error' => 'No table selected.'), 200); // 200 being the HTTP response code
            }

        }

        function find_id_post()
        {

            $this->load->library('class_model/booking');

            $trans_id=$this->input->get_post('trans_id');
            $type=$this->input->get_post('type');
            //$trans_id = 'cPGLThCq8FcHYNFVbuDuYNI4hkk=';

            $dbRet=$this->booking->FindId($trans_id, $type);

            $this->_proces_response($dbRet);

        }

        function update_booking_post()
        {

            $this->load->library('class_model/booking');
            $type=$this->input->get_post('type');
            $id=$this->input->get_post('id');

            $dbRet=$this->booking->UpdateStatus($type, $id);
            $this->response(array('affected_rows' => $dbRet), 200); // 200 being the HTTP response code 

        }

        function show_invoice_rentacar_post()
        {

            $this->load->library('class_model/invoice');

            $booking_id=$this->input->get_post('carbooking_id');
            //$booking_id = $this->get('carbooking_id');
            //$booking_id = 738;

            if(!isset($booking_id) || $booking_id == NULL)
            {
                $this->response(array('info' => 'No booking_id.'), 200); // 200 being the HTTP response code
                return FALSE;
            }

            $data=array();

            $dbRet=$this->invoice->ShowInvoice_car1($booking_id);
            $data[0]=$this->_proces_response_2($dbRet);

            $dbRet=$this->invoice->ShowInvoice_car2($booking_id);
            $data[1]=$this->_proces_response_2($dbRet);

            $this->response($data, 200); // 200 being the HTTP response code

        }

        function show_invoice_exc_post()
        {

            $this->load->library('class_model/invoice');

            $booking_id=$this->input->get_post('excursionbooking_id');
            //$booking_id = $this->get('carbooking_id');
            //$booking_id = 738;
//            $booking_id = 292;

            if(!isset($booking_id) || $booking_id == NULL)
            {
                $this->response(array('info' => 'No booking_id.'), 200); // 200 being the HTTP response code
                return FALSE;
            }

            $dbRet=$this->invoice->ShowInvoice_exc($booking_id);

            $dbRet=$this->translate->clean_asoc_array($dbRet, 'en');
//            $dbRet=$this->translate->res_array($dbRet, 'en');

            $this->response($dbRet, 200); // 200 being the HTTP response code

        }

        function show_invoice_tour_post()
        {

            $this->load->library('class_model/invoice');

            $booking_id=$this->input->get_post('tourbooking_id');
            //$booking_id = $this->get('carbooking_id');
            //$booking_id = 738;
            //$booking_id = 107;

            if(!isset($booking_id) || $booking_id == NULL)
            {
                $this->response(array('info' => 'No booking_id.'), 200); // 200 being the HTTP response code
                return FALSE;
            }

            $dbRet=$this->invoice->ShowInvoice_tour($booking_id);

            $dbRet=$this->translate->clean_asoc_array($dbRet, 'en');
            $dbRet=$this->translate->res_array($dbRet, 'en');

            $this->response($dbRet, 200); // 200 being the HTTP response code

        }

        private function _proces_response($dbRet)
        {

            if(!$dbRet)
            {
                $this->response(array('error' => $this->db->_error_message()), 200);
            }
            else if($dbRet->num_rows() == 0)
            {
                $this->response(array('num_rows' => $dbRet->num_rows()), 200);
            }
            else
            {

                $lang=$this->input->get_post('lang');

                //$this->firephp->log($lang);

                $dbRet=$this->translate->res_array($dbRet->result_array(), $lang);

                return $this->response($dbRet, 200); // 200 being the HTTP response code
            }

        }

        private function _proces_response_2($dbRet)
        {

            if(!$dbRet)
            {
                return array('error' => $this->db->_error_message());
            }
            else if($dbRet->num_rows() == 0)
            {
                return array('num_rows' => $dbRet->num_rows());
            }
            else
            {

                $lang=$this->input->get_post('lang');

                //$this->firephp->log($lang);

                $dbRet=$this->translate->res_array($dbRet->result_array(), $lang);

                return $dbRet;
            }

        }

        function action1_get()
        {

            $q='
            SELECT car.*, gallery.path as g_path, pictures.filename as f_name
            FROM car
            LEFT JOIN gallery ON car.id = gallery.`posts_ID`
            LEFT JOIN pictures ON gallery.ID = pictures.gallery_ID
            AND pictures.ID=
            (
            SELECT pictures.ID
            FROM pictures
            WHERE pictures.gallery_ID = gallery.ID
            ORDER BY pictures.order ASC, pictures.ID ASC
            LIMIT 0, 1  
            )
            where user_id = 7 AND action_1 = 1 order by day13price asc
            ';


            $dbRet=$this->db->query($q);
            $this->_proces_response($dbRet);
            //$this->response($dbRet, 200); // 200 being the HTTP response code

        }

        function action2_get()
        {

            $q='
            SELECT car.*, gallery.path as g_path, pictures.filename as f_name
            FROM car
            LEFT JOIN gallery ON car.id = gallery.`posts_ID`
            LEFT JOIN pictures ON gallery.ID = pictures.gallery_ID
            AND pictures.ID=
            (
            SELECT pictures.ID
            FROM pictures
            WHERE pictures.gallery_ID = gallery.ID
            ORDER BY pictures.order ASC, pictures.ID ASC
            LIMIT 1, 1  
            )
            where user_id = 7 AND action_2 = 1 order by day13price asc
            ';


            $dbRet=$this->db->query($q);
            $this->_proces_response($dbRet);

        }

    }

    